package com.nerve.android.cloudoffice.app.activity.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nerve.android.NerveActivityGroup;
import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.ViewOnId;
import org.nerve.android.ui.dialog.ConfirmDialog;
import org.nerve.android.ui.dialog.DialogHelper.ConfirmListener;
import org.nerve.android.ui.dialog.SingleInputDialog;
import org.nerve.android.ui.dialog.SpinnerDialog;
import org.nerve.util.DateUtil;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.NavigationActivity;
import com.nerve.android.cloudoffice.app.group.IndexGroupActivity;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.common.Resource;
import com.nerve.android.cloudoffice.domain.Daily;
import com.nerve.android.cloudoffice.domain.Department;
import com.nerve.android.cloudoffice.domain.Task;
import com.nerve.android.cloudoffice.domain.User;
import com.nerve.android.cloudoffice.service.NetService;
import com.nerve.android.cloudoffice.service.data.TaskData;

/**
 * @project: Cloudoffice
 * @file: TaskActivity.java
 * @package: com.nerve.android.cloudoffice.app.activity.task
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: Aug 16, 2013
 * @change log:
 */
@SuppressLint({ "UseSparseArrays", "HandlerLeak" })
@Acvitity(layout=R.layout.activity_task)
public class TaskActivity extends NavigationActivity implements OnClickListener, ConfirmListener{

	public static final int MENU_DEPARTMENT_TASK = 0;
	
	private static final int DAILY_LOAD = 2;
	
	private static final int UPDATE_ME_OK = 902;
	
	@ViewOnId(id=R.id.gridView1)
	private ListView listView;
	@ViewOnId(id=R.id.dateInfo)
	public TextView dateInfoTV;
	@ViewOnId(id=R.id.message_empty)
	private TextView emptyTV;
	@ViewOnId(id=R.id.dayList)
	private ListView dailyListView;
	@ViewOnId(id=R.id.dayThing)
	private TextView dailyTV;
	
	@ViewOnId(id=R.id.okBtn, clickListener="this")
	public Button departmentBtn;
	
	private SingleInputDialog inputDialog;
	
	private TextView[] picker;
	
	private TaskAdapter adapter;
	
	private int selectType;
	
	private User user;
	private Department department;
	private boolean isMe;
	
	private List<Task> taskList = new ArrayList<Task>();
	private List<Daily> dailyList = new ArrayList<Daily>();
	
	private DailyAdapter dailyAdapter;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			hideProgressDialog();
			switch(msg.what){
			case WORKER_OK:
				adapter.notifyDataSetChanged();
				break;
			case WORKER_FAIL:
				toast(Const.ERROR);
				break;
			case DAILY_LOAD:
				dailyAdapter.notifyDataSetChanged();
				break;
			case UPDATE_ME_OK:
				toast("修改成功");
				setNavTitle("销售额:" + user.getData1());
				break;
			}
		}
	};
	
	@Override
	protected void initUI() {
		super.initUI();
		
		picker = new TextView[4];
		picker[0] = (TextView)findViewById(R.id.today);
		picker[1] = (TextView)findViewById(R.id.week);
		picker[2] = (TextView)findViewById(R.id.month);
		picker[3] = (TextView)findViewById(R.id.year);
		
		bindClick();
		
		adapter = new TaskAdapter();
		listView.setEmptyView(emptyTV);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//跳转到查看任务
				Intent intent = new Intent(TaskActivity.this, ViewTaskActivity.class);
				putData(ViewTaskActivity.VIEW_TASK, taskList.get(arg2));
				intent.putExtra(ViewTaskActivity.IS_ME, isMe);
				startActivityForResult(intent, 1);
			}
			
		});
		
		dateInfoTV.setText(DateUtil.getDate("yyyy-MM-dd EEEE"));
		
		isMe = user.getId() == OfficeApplication.getLoginId() && department == null;
		
		if(isMe){
			if(OfficeApplication.isSaleManLogin())
				setNavTitle("销售额:" + 
						(user.getData1() == null || user.getData1().trim().length()==0
							?0:user.getData1())
						,
						R.drawable.ico_edit);
			else
				setNavTitle("我的任务");
			
			customNavigateRightButton("创建任务", true);
			
			if(user.getPosition() > User.EMPLOYEE)
				departmentBtn.setVisibility(View.VISIBLE);
		}else{
			setNavTitle(department.getName() + "的任务");
			
			departmentBtn.setVisibility(View.GONE);
		}
		
		new TaskWorker().execute();
		
		loadDaily();
	}
	
	private void loadDaily(){
		dailyTV.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDaily(-1);
			}
		});
		
		dailyAdapter = new DailyAdapter();
		dailyListView.setAdapter(dailyAdapter);
		
		new DailyListWorker().execute();
	}
	
	private void bindClick(){
		for(int i=0;i<picker.length;i++)
			picker[i].setOnClickListener(this);
	}
	
	private void showDaily(int index){
		if(index == -1){
			putData(DailyActivity.DAILY, null);
		}else{
			putData(DailyActivity.DAILY, dailyList.get(index));
		}
		
		Intent intent = new Intent(this, DailyActivity.class);
		startActivityForResult(intent, DAILY_LOAD);
	}
	
	@Override
	protected void initData() {
		Department id = (Department)getData(Const.SELECT_DEPARTMENT_ID, true);
		if(id != null)
			department = id;
		
		User u = (User)getData(Const.SELECT_USER_ID, true);
		
		if(u != null)
			user = u;
		else
			user = OfficeApplication.USER;
		
		TaskData.clearData();
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.okBtn){
			NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
			group.changeTab(IndexGroupActivity.DEPARTMENT_TASK);
			
			return ;
		}
		int type = -1;
		switch (v.getId()) {
		case R.id.today:
			type = TaskData.DAY;
			break;
		case R.id.week:
			type = TaskData.WEEK;
			break;
		case R.id.month:
			type = TaskData.MONTH;
			break;
		case R.id.year:
			type = TaskData.YEAR;
			break;
		}
		
		if(type == selectType)
			return ;
		
		selectType = type;
		changeTab();
		new TaskWorker().execute();
	}
	
	private void changeTab(){
		for(TextView tv : picker){
			tv.setTextColor(getResources().getColor(R.color.tab_select_no));
		}
		
		picker[selectType].setTextColor(getResources().getColor(R.color.tab_select));
	}
	
	@Override
	protected void onNavigateBackButtonClick() {
		NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
		group.changeTab(IndexGroupActivity.HOME);
	}
	
	@Override
	protected void onNavigateRightButtonClick() {
		NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
		group.next();
	}
	
	@Override
	protected void onNavigateTitleClick() {
		if(inputDialog == null){
			inputDialog = new SingleInputDialog(this);
			inputDialog.setDefaultText(user.getData1());
			inputDialog.setTitle("修改我的销售额");
			inputDialog.setConfirmListener(new ConfirmListener() {
				
				@Override
				public void onConfirmClick(int position, Object obj) {
					if(position == ConfirmDialog.OK){
						user.setData1(obj.toString());
						Const.log("------------> 新的销售额：" + user.getData1());
						showProgressDialog(null, "正在修改销售额...");
						new UpdateWorker().execute();
					}
				}
			});
		}
		inputDialog.show();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		//如果在addTaskActivity中增加任务成功，刷新任务数据
		Object addTask = getData(AddTaskActivity.LAST_TASK, true);
		Const.log("OnResume:" + addTask);
		if(addTask != null && (Integer)addTask == 1){
			TaskData.clearData();
			
			new TaskWorker().execute();
		}
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == DAILY_LOAD){
			Const.log("back from DailyActivity!");
			
			new DailyListWorker().execute();
		}
		else{
			if(isMe){
				TaskData.clearData();
				new TaskWorker().execute();
			}
		}
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Const.log("TaskActivity KEY DOEN!!!");
		
		if(keyCode == KeyEvent.KEYCODE_MENU){
			SpinnerDialog sd = new SpinnerDialog(this, new String[]{"查看部门任务"});
			sd.setTitle("菜单");
			sd.setConfirmListener(this);
			sd.show();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onConfirmClick(int position, Object obj) {
		if(position == 0){
			NerveActivityGroup group = getActivityGroup(IndexGroupActivity.class);
			
			group.changeTab(IndexGroupActivity.DEPARTMENT_TASK);
		}
	}
	
	
	private class TaskAdapter extends BaseAdapter{
		//获取宽度值
		private DisplayMetrics dm;
		
		public TaskAdapter(){
			dm = getResources().getDisplayMetrics();
		}
		
		@Override
		public int getCount() {
			return taskList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return taskList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			Task t = (Task)getItem(arg0);
			arg1 = View.inflate(TaskActivity.this, R.layout.activity_task_listitem, null);
			
			((TextView)arg1.findViewById(R.id.title)).setText(t.getTitle());
			((TextView)arg1.findViewById(R.id.date)).
				setText(
						DateUtil.toString(t.getStartDate(),
						selectType == R.id.year? "yyyy-MM-dd":"MM-dd"
						));
			
			RelativeLayout backL = (RelativeLayout)arg1.findViewById(R.id.process);
			setWidth(backL, t.getStatus());
			
			TextView locationV = (TextView)arg1.findViewById(R.id.location);
			
			if(department == null){
				if(t.getStatus() == 100){
					locationV.setText("√");
					locationV.setTextSize(18);
					locationV.setBackgroundDrawable(null);
				}else{
					locationV.setTextSize(12);
					locationV.setText(
							Resource.Task.LOCATION[t.getLoaction()]
							);
				}
			}else{
				locationV.setText(t.getWorkUser());
			}
			
			
			return arg1;
		}
		
		/**
		 * @method name: setWidth
		 * @description: 设置宽度
		 * @return type: void
		 *
		 * @param ll
		 * @param state
		 */
		private void setWidth(RelativeLayout ll, int state){
			int width = (dm.widthPixels * state) / 100;
			Const.log("width=" + width + ", state="+ state);
			try{
				RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)ll.getLayoutParams();
				lp.width = width;
				ll.setLayoutParams(lp);
			}catch(Exception e){
				e.printStackTrace(System.out);
			}
		}
		
	}
	
	private class TaskWorker extends AsyncTask<Void, Void, Integer>{

		@SuppressWarnings("unchecked")
		@Override
		protected Integer doInBackground(Void... params) {
			Reply re = TaskData.get(isMe?user.getId():0, department == null?0:department.getId(), selectType);
			if(re.isError())
				Const.ERROR = re.getMessage().toString();
			else{
				List<Task> tasks = (List<Task>)re.getMessage();
				if(tasks != null){
					taskList = tasks;
				}
			}
			
			return re.isError()? WORKER_FAIL:WORKER_OK;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
	}
	
	private class DailyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return dailyList.size();
		}

		@Override
		public Object getItem(int position) {
			return dailyList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null)
				convertView = View.inflate(TaskActivity.this, R.layout.activity_task_day_item, null);
			
			((TextView)convertView).setText(dailyList.get(position).getTitle());
			convertView.setTag(position);
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int index = Integer.valueOf(v.getTag().toString());
					
					showDaily(index);
				}
			});
			
			return convertView;
		}
		
	}
	
	private class DailyListWorker extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {
			Reply re = NetService.get(Const.HOST + "task/dailyList.htm");
			
			if(re.isError()){
				Const.ERROR = re.getMessage().toString();
				return WORKER_FAIL;
			}
			try{
				dailyList = JSON.parseArray(re.getMessage().toString(), Daily.class);
			}catch(Exception e){
				Const.log(e.toString());
			}
			
			return DAILY_LOAD;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			handler.sendEmptyMessage(result);
		}
	}
	
	 private class UpdateWorker extends AsyncTask<Void, Void, Integer>{

			@Override
			protected Integer doInBackground(Void... params) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("user.birthday", user.getBirthday());
				map.put("user.address", user.getAddress());
				map.put("user.header", user.getHeader());
				map.put("user.cellPhone", user.getCellPhone());
				map.put("user.sign", user.getSign());
				map.put("user.data1", user.getData1());
				
				Reply re = NetService.post(Const.HOST + "user/updateBatch.htm", map);
				if(re.isError()){
					Const.ERROR = re.getMessage().toString();
					return WORKER_FAIL;
				}
				
				return UPDATE_ME_OK;
			}
	    	
			@Override
			protected void onPostExecute(Integer result) {
				handler.sendEmptyMessage(result);
			}
	    }

}